package com.mall.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;

public class MallNestedScrollView extends NestedScrollView {
    private Context context;
    public MallNestedScrollView(@NonNull Context context) {
        super(context);
        init(context);
    }

    public MallNestedScrollView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MallNestedScrollView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        this.context = context;
        scrollSafeY = ViewConfiguration.get(context).getScaledTouchSlop();

    }

    private boolean isNeedScroll = true;
    private float xDistance, yDistance, xLast, yLast;
    private int scrollSafeY;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDistance = yDistance = 0f;
                xLast = ev.getX();
                yLast = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                xDistance += Math.abs(curX - xLast);
                yDistance += Math.abs(curY - yLast);
                xLast = curX;
                yLast = curY;
                if (yDistance > scrollSafeY) {
                    if (xDistance > yDistance) {
                        return false;
                    }
                    return isNeedScroll;
                }

        }
        return super.onInterceptTouchEvent(ev);
    }

    /*
改方法用来处理NestedScrollView是否拦截滑动事件
 */
    public void setNeedScroll(boolean isNeedScroll) {
        this.isNeedScroll = isNeedScroll;
    }

}
